package io.gitee.minelx.example.geohash;

import java.math.BigDecimal;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

public class Range {
    private final BigDecimal left;

    private final BigDecimal right;

    private final BigDecimal mid;

    private Range(BigDecimal left, BigDecimal right) {
        this.left = left;
        this.right = right;

        mid = right.add(left).divide(new BigDecimal("2"));
    }

    public List<Boolean> determines(BigDecimal value, int times) {
        List<Boolean> result = new ArrayList<>();
        Range current = this;
        for (int at = 0; at < times; at++) {
            result.add(current.determine(value));
            current = current.trace(value);
        }
        return result;
    }

    public List<Range> traces(BigDecimal value, int times) {
        List<Range> result = new ArrayList<>();
        Range current = this;
        for (int at = 0; at < times; at++) {
            result.add(current);
            current = current.trace(value);
        }
        return result;
    }

    public Range trace(BigDecimal value) {
        if (determine(value)) {
            return new Range(mid, right);
        }
        return new Range(left, mid);
    }

    public boolean determine(BigDecimal value) {
        return value.compareTo(mid) >= 1;
    }

    public BigDecimal left() {
        return left;
    }

    public BigDecimal right() {
        return right;
    }

    public static Range of(BigDecimal left, BigDecimal right) {
        return new Range(left, right);
    }

    @Override
    public String toString() {
        return "Range{" +
                "left=" + left +
                ", right=" + right +
                '}';
    }
}
